package dao

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"strconv"
)

type CollectESDAO struct {
	client *elastic.Client
}

func NewCollectESDAO(client *elastic.Client) *CollectESDAO {
	return &CollectESDAO{client: client}
}
func (dao *CollectESDAO) Search(ctx context.Context, uid int64, biz string) ([]int64, error) {
	query := elastic.NewBoolQuery().Must(
		elastic.NewTermQuery("uid", uid),
		elastic.NewTermQuery("biz", biz),
	)
	resp, err := dao.client.Search(CollectIndexName).Query(query).Do(ctx)
	if err != nil {
		return []int64{}, err
	}
	res := make([]int64, 0, len(resp.Hits.Hits))
	for _, hit := range resp.Hits.Hits {
		var tmp BizCollectInfo
		err = json.Unmarshal(hit.Source, &tmp)
		if err != nil {
			return nil, err
		}
		res = append(res, tmp.BizId)
	}
	return res, err
}

func (dao *CollectESDAO) InputCollectInfo(ctx context.Context, info BizCollectInfo) error {
	_, err := dao.client.Index().Index(CollectIndexName).
		Id(strconv.FormatInt(info.Id, 10)).
		BodyJson(info).Do(ctx)
	return err
}

type BizCollectInfo struct {
	Id    int64  `json:"id"` //收藏表里的主键 debug用
	Uid   int64  `json:"uid"`
	Biz   string `json:"biz"`
	BizId int64  `json:"biz_id"`
}
